package com.blemanager;

import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

import com.ble.*;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Administrator on 2016/9/21.
 */
public class BleManagerModule extends ReactContextBaseJavaModule implements ActivityEventListener, LifecycleEventListener {

    public static final String REACT_CLASS = "RNBleManagerModule";
    private static final String TAG = "BleManagerModule";
    public static ReactApplicationContext ctx = null;

    /*
    *ble code
     */
    private BlueToothConfig btconfig;
    public BluetoothLeService mBluetoothLeService;
    @Override
    public String getName() {
        return REACT_CLASS;
    }

    public BleManagerModule(ReactApplicationContext reactContext) {
        super(reactContext);
        ctx = reactContext;

        init_ble();

        reactContext.addActivityEventListener(this);
        reactContext.addLifecycleEventListener(this);
    }

    public void init_ble(){
        btconfig = new BlueToothConfig(ctx);
        if(!btconfig.checkBleOpen()){
            btconfig.openBle();
        }

        Intent gattServiceIntent = new Intent(ctx, BluetoothLeService.class);
//        if(gattServiceIntent == null)
//        	Log.d(TAG, "gattservice is null");

        ctx.bindService(gattServiceIntent, mServiceConnection, ctx.BIND_AUTO_CREATE);
        ctx.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());

        ctx.bindService(gattServiceIntent, mServiceConnection, ctx.BIND_AUTO_CREATE);
    }

    public List<BluetoothDevice> devices = new ArrayList<BluetoothDevice>();



    @ReactMethod
    public void test(){
//        Toast.makeText(getReactApplicationContext(), "123", Toast.LENGTH_SHORT).show();
        devices.clear();
        btconfig.setCallBack(new BlueToothConfig.ICallBack() {
            @Override
            public void execute(BluetoothDevice device, int rssi, byte[] scanRecord) {
                // TODO Auto-generated method stub
                if(rssi > -85){
                    if(!devices.contains(device)){
                        devices.add(device);
                        Log.d(TAG,device.getAddress() + String.valueOf(rssi));
                    }
                }
            }
        });

        btconfig.startBleScan();
    }

    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            Log.w(TAG,"start BluetoothLeService");
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
            if (!mBluetoothLeService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
//	            mIWebview.getActivity().finish();
            }

            Log.w(TAG, "mBluetoothLeService is okay");
            // Automatically connects to the device upon successful start-up initialization.
            //mBluetoothLeService.connect(mDeviceAddress);
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            // TODO Auto-generated method stub
            //mBluetoothLeService = null;
        }
    };

    private static IntentFilter makeGattUpdateIntentFilter() {                        //注册接收的事件
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_BLE_VERSION);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_PM25);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_TEHU);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_BATTERY);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_OVER);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_IBEACON_SERVICES_DISCOVERED);
        return intentFilter;
    }

//    private Handler mHandler = new Handler(){
//        @Override
//        public void handleMessage(Message msg) {
//        }
//    };
//    private Handler mHandler = new Handler(){
//        @Override
//        public void handleMessage(Message msg) {
//            String message = (String) msg.obj;
//            switch (msg.what) {
//                case 1003: {
//                    break;
//                }
//                case 1004: {
//                    break;
//                }
//                case 1005: {
//                    break;
//                }
//                case 1006: {
//                    break;
//                }
//                case 1009: {
//                    break;
//                }
//                case 1010: {
//                    boolean status = mBluetoothLeService.connect(message);
//                    break;
//                }
//                default:
//                    break;
//            }
//        }
//    };

    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent intent) {
            // TODO Auto-generated method stub
            final String action = intent.getAction();
            Log.w(TAG,"BroadcastReceiver() action is " + action);
            if(BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)){

            }else if(BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)){

            }else
            if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) { //可以开始干活了

            }else if(BluetoothLeService.ACTION_DATA_OVER.equals(action)){
//            	Log.d("test","112345");
            }else if(BluetoothLeService.ACTION_GATT_IBEACON_SERVICES_DISCOVERED.equals(action)){

            }
        }
    };

    @Override
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {

    }

    @Override
    public void onNewIntent(Intent intent) {

    }

    @Override
    public void onHostResume() {

    }

    @Override
    public void onHostPause() {

    }

    @Override
    public void onHostDestroy() {
        btconfig.stopBleScan();
    }
}
